package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.ResultData;


import com.itheima.ydd.dto.SysUserVo;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/sys_user")
public class SysAdminController {
    @Autowired //管理员
    private ISysUserService sysUserService;
    @Autowired //角色
    private ISysRoleService sysRoleService;



    @GetMapping("/list")
    public ResultData list(String login_name, String status, String phone, Long page, Long limit) {
        /**
         * 查询全部管理员信息
         *
         */
        //data数据map
        HashMap<String, Object> maps = new HashMap<>();

        // 1.查询所有管理员信息 分页待条件
        Page<SysUser> sysUserPage = new Page<>(page, limit);
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(login_name), SysUser::getLoginName, login_name);
        qw.eq(StringUtils.isNotEmpty(status), SysUser::getStatus, status);
        qw.eq(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);
        sysUserService.page(sysUserPage, qw);

        // 2.将分页信息放到map
        maps.put("count", sysUserPage.getTotal());
        maps.put("totalPages", sysUserPage.getPages());
        maps.put("pageSize", sysUserPage.getSize());
        maps.put("currentPage", sysUserPage.getCurrent());

        // 3.处理集合信息
        List<SysUser> SysUserList = sysUserPage.getRecords();
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        for (SysUser sysUser : SysUserList) {
            //拷贝信息到map
            HashMap<String, Object> userMap = new HashMap<>();

            userMap.put("id", sysUser.getId());
            userMap.put("login_name", sysUser.getLoginName());
            userMap.put("password", sysUser.getPassword());
            userMap.put("name", sysUser.getName());
            userMap.put("email", sysUser.getEmail());
            userMap.put("phone", sysUser.getPhone());
            userMap.put("login_ip", sysUser.getLoginIp());
            userMap.put("login_date", sysUser.getLoginDate());
            userMap.put("create_date", sysUser.getCreateDate());
            userMap.put("update_date", sysUser.getUpdateDate());
            userMap.put("del_flag", sysUser.getDelFlag());
            userMap.put("status", sysUser.getStatus());
            userMap.put("default_data", sysUser.getDefaultData());


            //根据role查询名字 是个数组字符串 装到集合
            ArrayList<Object> rolenameList = new ArrayList<>();
            String roleId = sysUser.getRoleId();
            String replaceStr = roleId.replace("[", "").replace("]", "").replace("\"", "");
            String[] split = replaceStr.split(",");
            userMap.put("role_id", split);
            for (String s : split) {
                String reId = s.trim();
                //根据角色id查询角色名字
                SysRole role = sysRoleService.getById(reId);
                rolenameList.add(role.getName());
            }
            userMap.put("rolename", rolenameList);

            dataList.add(userMap);

        }

        maps.put("data", dataList);

        return ResultData.ok("", maps);
    }


   // @ApiOperation("数据回显")
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        SysUser sysUser = sysUserService.getById(id);
        HashMap<String, Object> userMap = new HashMap<>();

        userMap.put("id", sysUser.getId());
        userMap.put("login_name", sysUser.getLoginName());
        userMap.put("name", sysUser.getName());
        userMap.put("email", sysUser.getEmail());
        userMap.put("phone", sysUser.getPhone());
        userMap.put("login_ip", sysUser.getLoginIp());
        userMap.put("login_date", sysUser.getLoginDate());
        userMap.put("create_date", sysUser.getCreateDate());
        userMap.put("update_date", sysUser.getUpdateDate());
        userMap.put("del_flag", sysUser.getDelFlag());
        userMap.put("status", sysUser.getStatus());
        userMap.put("default_data", sysUser.getDefaultData());

        String roleId = sysUser.getRoleId();
        String replaceStr = roleId.replace("[", "").replace("]", "").replace("\"", "");
        String[] split = replaceStr.split(",");
        userMap.put("role_id", split);

        return ResultData.ok("",userMap);
    }


    //@ApiOperation("修改信息")  // TODO 未完成
    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserVo sysUserVo) {

        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserVo.getId());
        sysUser.setLoginName(sysUserVo.getLoginName());
        sysUser.setName(sysUserVo.getName());
        sysUser.setEmail(sysUserVo.getEmail());
        sysUser.setPhone(sysUserVo.getPhone());
        sysUser.setLoginIp(sysUserVo.getLoginIp());
        sysUser.setLoginDate(sysUserVo.getLoginDate());
        sysUser.setCreateDate(sysUserVo.getCreateDate());
        sysUser.setUpdateDate(sysUserVo.getUpdateDate());
        sysUser.setStatus(sysUserVo.getStatus());
        sysUser.setDefaultData(sysUserVo.getDefaultData());

        //密码加密
        if (StringUtils.isNotEmpty(sysUserVo.getPassword())) {
            String pass = DigestUtils.md5DigestAsHex(sysUserVo.getPassword().getBytes());
            sysUser.setPassword(pass);
        }
        //处理数组
        List<String> roleId = sysUserVo.getRoleId();
        String join = StringUtils.join(roleId, ",");
        String role="["+join+"]";
        sysUser.setRoleId(role);

        sysUserService.updateById(sysUser);

        return ResultData.ok("", "");
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody SysUserVo sysUserVo) {

        List<String> roleIds = sysUserVo.getRoleId();
        for (String roleId : roleIds) {
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserVo, sysUser);
            if (StringUtils.isNotEmpty(sysUserVo.getPassword())) {
                String pass = DigestUtils.md5DigestAsHex(sysUserVo.getPassword().getBytes());
                sysUser.setPassword(pass);
            }
            sysUser.setId(UUID.randomUUID().toString());
            sysUser.setCreateDate(LocalDateTime.now());
            sysUser.setUpdateDate(LocalDateTime.now());
            sysUser.setRoleId(roleId);
            sysUserService.save(sysUser);
        }
        return ResultData.ok("", null);

    }

}
